package com.company.controller;


import com.company.entity.Phone;
import com.company.entity.User;
import com.company.service.MainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/main")
public class MainController {
    @Autowired
    MainService mainService;

    @RequestMapping("/index")
    public void index(HttpSession session, Model model) {
        User u = (User) session.getAttribute("LoginUser");
        List<Phone> list = mainService.queryUserPhones(u.getId());
        model.addAttribute("data", list);
    }

    @RequestMapping("/add")
    @ResponseBody
    public String add(String name, String tel, HttpSession session) {
        User u = (User) session.getAttribute("LoginUser");
        mainService.addPhone(name, tel, u.getId());
        return "success";
    }

    @RequestMapping("/del")
    public String del(int pid, HttpSession session) {
        User u = (User) session.getAttribute("LoginUser");
        mainService.delPhone(pid, u.getId());   //1.第pid条数据。2.用户的编号。
        return "redirect:/main/index.do";
    }

    @RequestMapping("/edit")
    public void edit(int pid, HttpSession session, Model model) {
        User u = (User) session.getAttribute("LoginUser");
        Phone p = mainService.queryPhone(pid, u.getId());
        model.addAttribute("p", p);

    }

    @RequestMapping("/editPost")
    public String editPost(int id, String name, String tel, HttpSession session) {
        User u = (User) session.getAttribute("LoginUser");
        Phone p = new Phone(id, name, tel, u.getId());
        mainService.editPhone(p);
        return "redirect:/main/index.do";
    }
}
